package com.imedway.ihe.dd.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.json.JSONUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.imedway.ihe.dd.dto.RetrieveDTO;
import com.imedway.ihe.dd.helper.Iti41ProvidedRegisterHelper;
import com.imedway.ihe.dd.helper.Iti43RetrieveHelper;
import com.imedway.ihe.dd.properties.ItiAddressProperties;
import com.imedway.ihe.dd.result.ResponseResult;
import com.imedway.ihe.dd.service.Iti43ClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.*;
import org.apache.camel.support.DefaultExchange;
import org.openehealth.ipf.commons.ihe.xds.core.requests.ProvideAndRegisterDocumentSet;
import org.openehealth.ipf.commons.ihe.xds.core.requests.RetrieveDocumentSet;
import org.openehealth.ipf.commons.ihe.xds.core.responses.Response;
import org.openehealth.ipf.platform.camel.core.util.Exchanges;
import org.openehealth.ipf.platform.camel.ihe.xds.core.converters.XdsRenderingUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/7/4
 */
@Slf4j
@RestController
@RequestMapping("/ihe/xds")
@RequiredArgsConstructor
@Api(tags = "XDS-Iti43文档获取")
public class Iti43ClientController {

    private final CamelContext camelContext;
    private final ProducerTemplate producerTemplate;
    private final Iti43ClientService iti43ClientService;
    private final ItiAddressProperties itiAddressProperties;

    @ApiOperation(value = "ITI41-文档提供与注册")
    @ApiOperationSupport(order = 1)
    @PostMapping(value = "iti43", consumes = "application/json")
    public Response iti43RetrieveDocument(@RequestBody RetrieveDTO retrieveDTO) throws IOException, InvalidPayloadException, ExecutionException, InterruptedException {
        Exchange exchange = new DefaultExchange(camelContext);
        exchange.setPattern(ExchangePattern.InOut);

        // 构建数据
        RetrieveDocumentSet request = Iti43RetrieveHelper.createRetrieveDocumentSet(retrieveDTO);

        // 发送请求
        exchange.getIn().setBody(request);

        log.debug("请求参数: \n" + XdsRenderingUtils.render(exchange));

        Exchange send = producerTemplate.send("xds-iti43://" + itiAddressProperties.getIti43Location(), exchange);


        Map<String, Object> headers = send.getMessage().getHeaders();
        headers.forEach((k, v) -> log.debug("请求头: " + k + "=" + v));

        return send.getMessage().getMandatoryBody(Response.class);
    }

}
